package com.huika.renrench.control.main.epship.acty;

import java.util.ArrayList;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.main.epship.adap.EntrepreneurshipProjectAdapter;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.EnshipProject;
import com.huika.renrench.support.bean.LocationBean;
import com.huika.renrench.support.bean.LocationBean.MyLocationListener;
import com.huika.renrench.utils.GaodeMapHelper;
import com.huika.renrench.view.TitleBarHelper;

public class SerchProject extends BaseAct implements
		Listener<RequestResult<ArrayList<EnshipProject>>>,
		OnRefreshListener2<ListView> ,OnItemClickListener, MyLocationListener {

	private TitleBarHelper titleBarHelper;
	private EditText searchContent_et;
	private ImageView clearContent_img;
	/** 列表适配器 */
	private EntrepreneurshipProjectAdapter adapter;
	/** 列表 */
	private PullToRefreshListView enshipLv;
	/** 空数据的布局 */
	private View nullView;
	
	private String content;
	private LocationBean locationBean=new LocationBean();
	private GaodeMapHelper gaodeMapHelper;
	

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		super.initData();
//		locationBean=GlobalApp.getInstance().locationBean;
//		if (GlobalApp.getInstance().isLocated()) {
//			getDataFromNet(typeId, areaId, price, "",locationBean.latitude,locationBean.longtitude);
//		}else{
			startLocation();
//		}
		
	}

	@Override
	public void setRootView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_serch_project);
		initTopBar();
		initViews();
		initListener();
	}

	/**
	 * @author cy
	 * @date 2015年6月3日,上午9:57:39
	 */
	private void initListener() {
		// TODO Auto-generated method stub
		titleBarHelper.setOnRightClickListener(this);
		clearContent_img.setOnClickListener(this);
		searchContent_et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.length() > 0) {
					clearContent_img.setVisibility(View.VISIBLE);
				} else {
					clearContent_img.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.right:
			content = searchContent_et.getText().toString();
			if (checkInput(content)) {
				getDataFromNet("", "", "", content,locationBean.latitude+"",locationBean.longtitude+"");
			}
			break;
		case R.id.clear_content_icon:
			searchContent_et.setText("");
			break;

		default:
			break;
		}
	}

	private boolean checkInput(String content) {
		if (!TextUtils.isEmpty(content)) {
			return true;
		}
		showToastMsg("搜索内容不能为空！");
		return false;
	}

	/**
	 * @author cy
	 * @date 2015年6月3日,上午9:57:36
	 */
	private void initViews() {
		// TODO Auto-generated method stub
		nullView = findViewById(R.id.null_layout);
		/** 列表 */
		enshipLv = (PullToRefreshListView) findViewById(R.id.enshipLv);
		adapter = new EntrepreneurshipProjectAdapter(this);
		enshipLv.setAdapter(adapter);
		enshipLv.setOnRefreshListener(this);
		enshipLv.setOnItemClickListener(this);
	}

	private void initTopBar() {
		// TODO Auto-generated method stub
		titleBarHelper = new TitleBarHelper(this, R.string.common_null,
				R.string.common_search, true);

		searchContent_et = titleBarHelper.getSearchContent_et();
		clearContent_img = titleBarHelper.getClearIcon_img();
	}

	private void getDataFromNet(String typeId, String areaId, String priceId,
			String projectName,String latitude,String longitude) {
		// TODO Auto-generated method stub
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();

		ajaxParams.putCommonTypeParam("projectName", projectName);
		
		ajaxParams.putCommonTypeParam("userId", "0");
		ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
		ajaxParams.putCommonTypeParam("pageSize", PAGE_SIZE);
		
		if (!TextUtils.isEmpty(latitude)) {
			ajaxParams.putCommonTypeParam("latitude", latitude);
		}
		if (!TextUtils.isEmpty(longitude)) {
			 ajaxParams.putCommonTypeParam("longitude", longitude);
		}
		
		if (!TextUtils.isEmpty(typeId)) {
			ajaxParams.putCommonTypeParam("typeId", typeId);
		}
		if (!TextUtils.isEmpty(priceId)) {
			ajaxParams.putCommonTypeParam("learnPrice", priceId);
		}
		if (!TextUtils.isEmpty(areaId)) {
			ajaxParams.putCommonTypeParam("areaId", areaId);
		}
		FormResultRequest<ArrayList<EnshipProject>> getResultRequest = new FormResultRequest<ArrayList<EnshipProject>>(
				UrlConstants.URL_FIND_PROJECTS, this, this,
				new TypeToken<RequestResult<ArrayList<EnshipProject>>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		getResultRequest.setRetryPolicy(new DefaultRetryPolicy(30 * 1000, 1, 1.0f));
		executeRequest(getResultRequest);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> arg0) {
		// TODO Auto-generated method stub
		if (checkInput(content)) {
			CURRENT_PAGE=1;
			getDataFromNet("", "", "", content,locationBean.latitude+"",locationBean.longtitude+"");
		}
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> arg0) {
		// TODO Auto-generated method stub
		if (checkInput(content)) {
			CURRENT_PAGE++;
			getDataFromNet("", "", "", content,locationBean.latitude+"",locationBean.longtitude+"");
		}
		
	}

	@Override
	public void onResponse(RequestResult<ArrayList<EnshipProject>> result) {
		// TODO Auto-generated method stub
		enshipLv.onRefreshComplete();
		if (result.flag == 1) {
			if (result != null && result.getRs() != null
					&& result.getRs().size() > 0) {
				setNullView(false);
				setListData(result.getRs());
				changeRefreshMode(result.getTotalSize());
			} else {
				setNullView(true);
			}
		} else {
			showToastMsg(result.msg);
		}
		dismissLoadingDialog();
	}

	private void setNullView(boolean isShow) {
		if (isShow) {
			enshipLv.setVisibility(View.GONE);
			nullView.setVisibility(View.VISIBLE);
		} else {
			enshipLv.setVisibility(View.VISIBLE);
			nullView.setVisibility(View.GONE);
		}
	}
	
	private void setListData(ArrayList<EnshipProject> rs) {
		if (CURRENT_PAGE == 1) {
			adapter.setGroup(rs);
		} else {
			adapter.addItems(rs);
		}
//		enshipLv.setAdapter(adapter);
	}
	
	private void changeRefreshMode(int totalSize) {
		if (adapter.getCount() < totalSize) {
			enshipLv.setMode(Mode.BOTH);
		} else {
			enshipLv.setMode(Mode.PULL_FROM_START);
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		int realPos = position - ((ListView) parent).getHeaderViewsCount();
		if (realPos >= 0 && realPos < adapter.getCount()) {
			EnshipProject addressBean = (EnshipProject) adapter
					.getItem(realPos);
			Intent show = new Intent(this, EnProjectDetailActivity.class);
			show.putExtra(EnProjectDetailActivity.PROJECT_TAG, addressBean);
			startActivity(show);
		}
	}
	
	private void startLocation() {
		showLoadingDialog("定位中");
		gaodeMapHelper = new GaodeMapHelper(this);
		gaodeMapHelper.setmLocationListener(this);
		gaodeMapHelper.start();
	}

	@Override
	public void onStop() {
		super.onStop();
		if(gaodeMapHelper != null){
			gaodeMapHelper.stop();
		}
	}

	@Override
	public void onLocation(LocationBean locationBean) {
		// TODO Auto-generated method stub
		dismissLoadingDialog();
		if(!TextUtils.isEmpty(locationBean.province)){
			this.locationBean=locationBean;
			GlobalApp.getInstance().setLocated(true);
		}else{//定位失败
			showToastMsg("定位失败");
			GlobalApp.getInstance().setLocated(false);
		}
		if(gaodeMapHelper != null){
			gaodeMapHelper.stop();
		}
	}

}
